<template>
  <div >
    <!-- 头部导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>食品更改</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.native.prevent
      style="width:460px;margin-left:50px;margin-top:20px"
    >
      <el-form-item label="食品名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="食品种类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择食品种类">
          <el-option
            v-for="(item,index) in options"
            :key="index"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="食品价钱" prop="price">
        <el-input v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label="食品库存" prop="stock">
        <el-input-number
          v-model="form.stock"
          @change="handleChange"
          :min="1"
          :max="100"
          label="描述文字"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="食品简介" prop="brief">
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.brief"></el-input>
      </el-form-item>
      <el-form-item label="预览图">
        <el-upload
          class="upload-demo"
          action="files/"
          :on-preview="handlePreview"
          :on-remove="previewRemove"
          :on-success="previewSuccess"
          :file-list="previewList"
          list-type="picture"
          :limit="1"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2Mb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情图">
        <el-upload
          class="upload-demo"
          action="files/"
          :on-preview="handlePreview"
          :on-remove="detailsRemove"
          :on-success="detailsSuccess"
          :file-list="detailsList"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2Mb</div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="goodsUpdate">立即修改</el-button>
        <el-button type="warning" @click="$router.push('/goodsList')">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapActions } = createNamespacedHelpers("category"); //从vuex获取食品类别数据
export default {
  props: ["_id"],
  data() {
    return {
      form: {
        /* name: '',//名字
          price:'',//价钱
          brief: '',//简介
          categoryId:'',//商品类id
          stock:1,//库存
          previewSrc:'',//预览图路径
          detailsSrc:[],//详情图路径数组
           */
      },
      previewList: [],
      detailsList: [],
      rules: {
          name: [
            { required: true, message: '请输入食品名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入价格', trigger: 'blur' },
            { type: 'number', message: '价格必须为数字'}
          ],
          categoryId: [
            { required: true, message: '请选择食品类别', trigger: 'change' }
          ],
          brief: [
             { required: true, message: '请填写食品简介', trigger: 'blur' }
          ]
        }
    };
  },
  computed: {
    // options(){
    //   return[{name:'油炸食品',_id:'1'},{name:'面食',_id:'2'}];//模拟数据，应该是vuex返回的数据
    // }
    ...mapState(["options"])
  },
  methods: {
    detailsRemove(file, fileList) {
      // console.log(file, fileList);
      //当x掉预览图后需要把数组中对应的图片链接删除
      this.form.detailsSrc = this.form.detailsSrc.filter(
        item => item != file.response
      );
    },
    previewRemove(file, fileList) {
      this.form.previewSrc = "";
      // console.log(this.form.previewSrc);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleChange(value) {
      console.log(value);
    },
    goodsUpdate() {
      axios.put("/goods", this.form).then(res => {
        if (res.data) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    //上传详情图片成功时
    detailsSuccess(res, file, fileList) {
      this.form.detailsSrc.push(res);
      //  这里可以获得图片上传成功的相关信息
      // console.log(res)
      // console.log(file)
      // console.log(fileList)
    },
    previewSuccess(res, file, fileList) {
      this.form.previewSrc = res;
      //  console.log(this.form.previewSrc);
    },
    getGoodsOne: function() {
      axios.get(`/goods/${this._id}`).then(res => {
        this.form = res.data[0];
        if(this.form.previewSrc!=""){
          this.previewList.push({ url: this.form.previewSrc });
        }
        
        this.detailsList = this.form.detailsSrc.map((item, index) => {
          return { name: "图" + index, url: item, response: item };
        });
      });
    },
    ...mapActions(["getCategoryAsync"])
  },
  mounted() {
    this.getGoodsOne();
    this.getCategoryAsync();
  }
  //组件离开守卫，暂时有点问题
  /* beforeRouteLeave(to, from, next) {
        axios.get("/goods/", { params: this.from }).then(res => {
            if (res.data.length == 0) {
                const answer = window.confirm(
                    "Do you really want to leave? you have unsaved changes!"
                );
                if (answer) {
                    next();
                } else {
                    next(false);
                }
            }else{
              next();
            }
        });
    } */
};
</script>

<style>
</style>